import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {

      const permission_routes = store.getters.permission_routes
      if (permission_routes.length) {
        next()
      } else {
        await store.dispatch('permission/getPermissionMemus').catch(() => {
          next({
            path: '/login'
          })
        })
        const accessRoutes = await store.dispatch('permission/generateRoutes')
        router.addRoutes(accessRoutes)
        router.addRoutes([{
          path: '*',
          redirect: '/404',
          hidden: true
        }])
        next({
          ...to,
          replace: true
        })
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
